<template>
  <button ref="triggerRef" @click="openDateSelector">打开日期选择</button>
  <view
    :class="[isMobile?'date-picker-mask':'']"
    v-if="isShow"
    @click="onMaskClick"
    :style="{ position: isMobile ? 'fixed' : 'absolute', top: positionTop, left: positionLeft }"
  >
    <view class="date-picker-dialog" :style="{ bottom: isShow ? '0' : '-100%' }">
      <view :class="[isMobile?'dialog-header':'dialog-header2']">
        <view class="cancel-btn" @click="isShow = false">取消</view>
        <view class="title">{{ title }}</view>
        <view class="confirm-btn" @click="onConfirm">确认</view>
      </view>
      <picker-view
        class="picker-view"
        :value="pickerValue"
        @change="onPickerChange"
        :indicator-style="indicatorStyle"
        :mask-style="{ opacity: '0.5' }"
      >
        <picker-view-column>
          <view
            class="picker-item"
            :style="getItemStyle(index, 'year')"
            v-for="(year, index) in years"
            :key="year"
          >
            {{ year }}
          </view>
        </picker-view-column>
        <picker-view-column>
          <view
            class="picker-item"
            :style="getItemStyle(index, 'month')"
            v-for="(month, index) in months"
            :key="month"
          >
            {{ month }}
          </view>
        </picker-view-column>
        <picker-view-column>
          <view
            class="picker-item"
            :style="getItemStyle(index, 'day')"
            v-for="(day, index) in days"
            :key="day"
          >
            {{ day }}
          </view>
        </picker-view-column>
      </picker-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
const props = defineProps({
  title: {
    type: String,
    default: '选择日期'
  },
  minDate: {
    type: String,
    default: '2018-01-01'
  },
  maxDate: {
    type: String,
    default: () => {
      const now = new Date()
      return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`
    }
  }
})

const isShow = ref(false)
const pickerValue = ref([0, 0, 0])
const systemInfo = uni.getSystemInfoSync()
const screenHeight = systemInfo.screenHeight
const [maxYear, maxMonth, maxDay] = props.maxDate.split('-').map(Number)
const [minYear, minMonth, minDay] = props.minDate.split('-').map(Number)
const triggerRef = ref(null)
const isMobile = ref(false);
const positionTop = ref('')
const positionLeft = ref('')
// 组件挂载时初始化
onMounted(() => {
  checkIsMobile();
  initDefault();
  console.log(isMobile.value)
})
// 打开日期选择器
const openDateSelector = () => {
  isShow.value = true;
  if (!isMobile.value && triggerRef.value) {
    const rect = triggerRef.value.getBoundingClientRect();
    positionTop.value = `${rect.bottom}px`;
    positionLeft.value = `${rect.left}px`;
  }
};
//判断是否为手机端
const checkIsMobile = () => {
  if (typeof navigator !== 'undefined') {
    isMobile.value = /Android|iPhone/i.test(navigator.userAgent);
  }
};
//计算年份列表
const years = ref([])
for (let y = minYear; y <= maxYear; y++) {
  years.value.push(y)
}
//计算月份列表
const months = ref([])
const generateMonths = (year) => {
  const monthList = []
  const startMonth = year === minYear ? minMonth : 1
  const endMonth = year === maxYear ? maxMonth : 12
  for (let m = startMonth; m <= endMonth; m++) {
    monthList.push(m.toString().padStart(2, '0'))
  }
  months.value = monthList
}
//计算日期列表
const days = ref([])
const generateDays = (year, month) => {
  const dayList = []
  const isMaxYear = year === maxYear
  const isMaxMonth = month === maxMonth
  const lastDay = new Date(year, month, 0).getDate()
  const startDay = (year === minYear && month === minMonth) ? minDay : 1
  const endDay = isMaxYear && isMaxMonth ? maxDay : lastDay
  for (let d = startDay; d <= endDay; d++) {
    dayList.push(d.toString().padStart(2, '0'))
  }
  days.value = dayList
}
//选中时的年月日
const selectedYear = computed(() => years.value[pickerValue.value[0]])
const selectedMonth = computed(() => Number(months.value[pickerValue.value[1]]))
const selectedDay = computed(() => Number(days.value[pickerValue.value[2]]))
// 初始化默认选中
const initDefault = () => {
  generateMonths(maxYear)
  generateDays(maxYear, maxMonth)
  pickerValue.value = [
    years.value.indexOf(maxYear),
    months.value.indexOf(maxMonth.toString().padStart(2, '0')),
    days.value.indexOf(maxDay.toString().padStart(2, '0'))
  ]
}
// picker-view 滑动事件
const onPickerChange = (e) => {
  pickerValue.value = e.detail.value
  if (e.detail.value[0] !== pickerValue.value[0]) {
    generateMonths(selectedYear.value)
    generateDays(selectedYear.value, selectedMonth.value)
  } else if (e.detail.value[1] !== pickerValue.value[1]) {
    generateDays(selectedYear.value, selectedMonth.value)
  }
}
// 监听年份变化
watch(() => pickerValue.value[0], () => {
  generateMonths(selectedYear.value)
  pickerValue.value[1] = 0
  generateDays(selectedYear.value, selectedMonth.value)
  pickerValue.value[2] = 0
})
// 监听月份变化
watch(() => pickerValue.value[1], () => {
  generateDays(selectedYear.value, selectedMonth.value)
  pickerValue.value[2] = 0
})

// 确认按钮事件
const emit = defineEmits(['confirm'])
const onConfirm = () => {
  const selectedDate = `${selectedYear.value}-${selectedMonth.value.toString().padStart(2, '0')}-${selectedDay.value.toString().padStart(2, '0')}`
  emit('confirm', selectedDate)
  isShow.value = false
}
// 计算指示器样式
const indicatorStyle = computed(() => {
  return `
    height: 50px;
    border-top: 1px solid #e0e0e0;
    border-bottom: 1px solid #e0e0e0;
    background-color: transparent;
    z-index: 1;
  `
})
// 动态计算每个选项的样式
const getItemStyle = (index, column) => {
  const currentIndex = pickerValue.value[column === 'year' ? 0 : column === 'month' ? 1 : 2]
  const distance = Math.abs(index - currentIndex)
  const baseStyle = {
    fontSize: '18px',
    color: '#666',
    fontWeight: 'normal',
    backgroundColor: 'transparent',
    height: '50px',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    transition: 'all 0.2s ease'
  }

  if (index === currentIndex) {
    return {
      ...baseStyle,
      fontSize: '20px',
      color: '#000000',
      fontWeight: 'bold',
      backgroundColor: '#ebebeb', // 更明显的背景色
      borderRadius: '8px',
      boxShadow: '0 0 10px #cacaca',
    }
  }
  return {
    ...baseStyle,
    fontSize: `${16 - distance * 0.5}px`,
    color: distance > 2 ? '#999' : '#666'
  }
}
</script>

<style scoped>
.date-picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 999;
}

.date-picker-dialog {
  width: 80%;
  max-width: 320px;
  background-color: #fff;
  border-radius: 12px;
  transition: bottom 0.3s ease;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: 4px solid #fdcd6e;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 20px;
  background-color: #fdcd6e;
}
.dialog-header2 {
  display: flex;
  margin-left: -25px;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 30px;
  background-color: #fdcd6e;
}

.cancel-btn,
.confirm-btn {
  color: #fff;
  font-size: 16px;
   white-space: nowrap; 
}
.title {
  font-size: 17px;
  font-weight: bold;
  color: #fff;
  white-space: nowrap; 
}
.picker-view {
  position: relative;
  width: 100%;
  height: 250px;
  z-index: 1;
}
.picker-item {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  padding: 0;
  margin: 0;
  position: relative;
  z-index: 3;
}
</style>